package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.dto.DeviceDto;
import com.zzyl.nursing.domain.pojo.Device;
import com.zzyl.nursing.domain.vo.DeviceDetailVo;
import com.zzyl.nursing.domain.vo.ProductVo;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 设备Service业务层处理
 *
 * @author alexis
 * @date 2025-05-28
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient ioTDAClient;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //从iot平台获取产品列表
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse listProductsResponse = ioTDAClient.listProducts(request);
        if (listProductsResponse.getHttpStatusCode() != 200) {
            throw new ServiceException("调取iot接口异常");
        }
        List<ProductSummary> products = listProductsResponse.getProducts();
        //将数据缓存至redis中
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
    }

    /**
     * 查询所有产品列表
     */
    @Override
    public List<ProductVo> getAllProduct() {
        //通过redis模版对象获取productVo的json字符串对象
        String productsVo = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //json字符串对象反序列化为集合对象
        List<ProductVo> productVos = JSONUtil.toList(productsVo, ProductVo.class);
        return productVos; //返回
    }

    /**
     * 注册设备
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.校验设备
        //校验设备名称重复
        Long deviceCount = this.lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName())
                .count();
        if (deviceCount > 0) {
            throw new ServiceException("设备名称重复");
        }
        //校验设备标识重复
        Long nodeCount = this.lambdaQuery()
                .eq(Device::getNodeId, deviceDto.getNodeId())
                .count();
        if (nodeCount > 0) {
            throw new ServiceException("设备标识重复");
        }
        //校验同一位置绑定了相同的产品
        Long sameCount = this.lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(ObjectUtil.isNotNull(deviceDto.getPhysicalLocationType()), Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .count();
        if (sameCount > 0) {
            throw new ServiceException("同一位置不能绑定相同的产品");
        }
        //2.注册设备
        //第二步:根据addDevice方法所需的request对象进行创建
        AddDeviceRequest request = new AddDeviceRequest();
        //第三步:根据官方api要求必须添加的body参数添加属性
        AddDevice body = new AddDevice();
        body.withNodeId(deviceDto.getNodeId());
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        //第一步:调取华为官方api方法
        AddDeviceResponse addDeviceResponse = ioTDAClient.addDevice(request);

        if (addDeviceResponse.getHttpStatusCode() != 201) {
            throw new ServiceException("注册设备失败");
        }
        //本地保存设备(补全dto与pojo中缺失的属性),返回pojo
        String iotId = addDeviceResponse.getDeviceId();
        String secret = addDeviceResponse.getAuthInfo().getSecret();
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //从redis缓存中获取产品名称并赋值给pojo返回
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        List<ProductVo> list = JSONUtil.toList(jsonStr, ProductVo.class);
        list.forEach(productVo -> {
            if (productVo.getProductId().equals(deviceDto.getProductKey())) {
                device.setProductName(productVo.getName());
            }
        });
        device.setIotId(iotId);
        device.setSecret(secret);
        this.save(device);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {

        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 获取设备详细信息
     */
    @Override
    public DeviceDetailVo selectDeviceBy(String iotId) {
        //查询数据库字段
        Device device = this.lambdaQuery()
                .eq(Device::getIotId, iotId)
//                .eq(Device::getProductKey, deviceDto.getProductKey())
                .one();
        if (ObjectUtil.isNull(device)) {
            return null;
        }

        //查询iot接口字段
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = ioTDAClient.showDevice(request);
        if (showDeviceResponse.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new ServiceException("获取设备信息失败");
        }
        //构建返回结果
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //补全属性
        deviceDetailVo.setDeviceStatus(showDeviceResponse.getStatus());
        deviceDetailVo.setProductName(showDeviceResponse.getProductName());
        String activeTime = showDeviceResponse.getActiveTime();
        // 日期时间字符串----转换成--->LocalDateTime
        if (StrUtil.isNotBlank(activeTime)) {
            LocalDateTime activeDateTime = LocalDateTime.parse(activeTime, DateTimeFormatter.ofPattern(DatePattern.UTC_MS_PATTERN));
            activeDateTime = activeDateTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeDateTime);
        }
        return deviceDetailVo;
    }

    /**
     * 获取设备运行数据
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        //根据设备id在iot平台查询设备影子接口,拿到properties对象
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse showDeviceShadowResponse = ioTDAClient.showDeviceShadow(request);
        if (showDeviceShadowResponse.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new ServiceException("获取设备不存在物模型数据");
        }

        //从iot设备影子响应数据中拿到接口文档中的properties
        List<DeviceShadowData> shadow = showDeviceShadowResponse.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            throw new ServiceException("获取设备不存在物模型属性");
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        if (ObjectUtil.isNull(reported)) {
            throw new ServiceException("获取物模型数据失败");
        }
        LocalDateTime parseLocalDateTime = LocalDateTimeUtil.parse(reported.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = parseLocalDateTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        ArrayList<Map<String, Object>> mapList = new ArrayList<>();
        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = MapUtil.<String, Object>builder()
                    .put("functionId", k)
                    .put("value", v)
                    .put("eventTime", eventTime)
                    .build();
            mapList.add(map);

        });
        return AjaxResult.success(mapList);
    }

    /**
     * 修改设备
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {

        //数据库修改
        this.update(Wrappers.lambdaUpdate(Device.class)
                .eq(Device::getNodeId, deviceDto.getNodeId())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .set(Device::getDeviceName, deviceDto.getDeviceName())
                .set(Device::getLocationType, deviceDto.getLocationType())
                .set(Device::getRemark, deviceDto.getRemark()));

        //华为云iot修改
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse updateDeviceResponse = ioTDAClient.updateDevice(request);
        if (updateDeviceResponse.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new ServiceException("修改设备失败");
        }
    }

    /**
     * 删除设备
     */
    @Override
    public void deleteById(String iotId) {
        //删除数据库字段
        this.remove(Wrappers.lambdaQuery(Device.class)
                .eq(Device::getIotId, iotId));

        //删除iot平台字段
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = ioTDAClient.deleteDevice(request);
        if (deleteDeviceResponse.getHttpStatusCode() != HttpStatus.NO_CONTENT) {
            throw new ServiceException("删除设备失败");
        }
    }

    /**
     * 查询产品详情
     *
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = ioTDAClient.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
